package com.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.app.mapper.PersonMapper;
import com.app.model.PersonModel;
import com.app.service.AdminUserService;
import com.app.service.PersonService;
import com.app.util.Result;
import com.app.vo.NameAndValueVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Primary
public class PersonServiceImpl  extends ServiceImpl<PersonMapper, PersonModel> implements PersonService {
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private AdminUserService adminUserService;

    @Override
    public Page<PersonModel> getPagePersonList(PersonModel personModel, List<Integer> idList, List<Integer> ids) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        //姓名
        if (StrUtil.isNotBlank(personModel.getKeywords())) {
            queryWrapper.like("name", personModel.getKeywords());
        }
        //手机号
        if (StrUtil.isNotBlank(personModel.getPhone())) {
            queryWrapper.like("phone", personModel.getPhone());
        }
        //性别
        if (StrUtil.isNotBlank(personModel.getGender())) {
            queryWrapper.like("gender", personModel.getGender());
        }
        //身份证号
        if (StrUtil.isNotBlank(personModel.getIdcard())) {
            queryWrapper.like("idcard", personModel.getIdcard());
        }
        //军官证号
        if (StrUtil.isNotBlank(personModel.getSergeantNumber())) {
            queryWrapper.like("sergeant_number", personModel.getSergeantNumber());
        }
        //部职别
        if (StrUtil.isNotBlank(personModel.getPositionDesc())) {
            queryWrapper.like("position_desc", personModel.getPositionDesc());
        }
        //行政职务
        if (StrUtil.isNotBlank(personModel.getAdministrativePosition())) {
            queryWrapper.like("administrative_position", personModel.getAdministrativePosition());
        }
        //军衔等级
        if (StrUtil.isNotBlank(personModel.getRankTitle())) {
            queryWrapper.like("rank_title", personModel.getRankTitle());
        }
        //岗位层级
        if (StrUtil.isNotBlank(personModel.getPositionLevel())) {
            queryWrapper.like("position_level", personModel.getPositionLevel());
        }
        //待遇级别
        if (StrUtil.isNotBlank(personModel.getTreatmentLevel())) {
            queryWrapper.like("treatment_level", personModel.getTreatmentLevel());
        }
        //籍贯
        if (StrUtil.isNotBlank(personModel.getNativePlace())) {
            queryWrapper.like("native_place", personModel.getNativePlace());
        }
        //民族
        if (StrUtil.isNotBlank(personModel.getNationText())) {
            queryWrapper.like("nation_text", personModel.getNationText());
        }
        //婚姻状况
        if (StrUtil.isNotBlank(personModel.getMaritalStatusText())) {
            queryWrapper.like("marital_status_text", personModel.getMaritalStatusText());
        }
        //部门单位
        if (personModel.getDepartmentId() != null) {
            queryWrapper.eq("department_id", personModel.getDepartmentId());
        }
        if (personModel.getZzmm() != null) {
            queryWrapper.eq("zzmm", personModel.getZzmm());
        }
        if (personModel.getDepIds() != null && personModel.getDepIds() != 1) {
            queryWrapper.eq("department_id", personModel.getDepIds());
        }
        if (idList != null && !idList.isEmpty()) {
            queryWrapper.in("department_id", idList);
        }
        if (personModel.getSortType() != null && personModel.getSortType() == 1) {
            queryWrapper.orderByDesc("serial_number").orderByDesc("create_time");
        } else {
            queryWrapper.orderByAsc("serial_number").orderByDesc("create_time");
        }
        queryWrapper.eq("status", 1);
        Page<PersonModel> pages = new Page<>();
        pages.setCurrent(personModel.getPage());
        pages.setSize(personModel.getLimit());
        return personMapper.selectPage(pages, queryWrapper);
    }

    @Override
    public Page<PersonModel> getPageTrainList(Integer page, Integer limit, String name, List<Integer> idList) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "serial_number", "name", "department_id", "position_desc", "gender");
        if (idList == null || idList.size() <= 0) {
            queryWrapper.select().like("name", name);
        } else {
            queryWrapper.in("department_id", idList);
            queryWrapper.select().like("name", name);
        }
        queryWrapper.ne("status", 0).orderByAsc("serial_number");
        Page<PersonModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<PersonModel> personList = personMapper.selectPage(pages, queryWrapper);
        return personList;
    }

    @Override
    public Page<PersonModel> getPageEnjoyList(Integer page, Integer limit, String name, List<Integer> idList) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "serial_number","name", "department_id", "rank_title", "gender","actual_job","idcard","position_desc");
        if (idList == null || idList.size() <= 0) {
            queryWrapper.select().like("name", name);
        } else {
            queryWrapper.in("department_id", idList);
            queryWrapper.select().like("name", name);
        }
        queryWrapper.ne("status", 0).orderByAsc("serial_number");
        Page<PersonModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<PersonModel> personList = personMapper.selectPage(pages, queryWrapper);
        return personList;
    }

    @Override
    public PersonModel selectPersonById(int id) {
        return personMapper.selectById(id);
    }

    @Override
    public Integer getPersonCount(Integer departmentId) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("department_id", departmentId);
        return personMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer PersonCount(List<Integer> depIdsList) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("status", 1);
        if (depIdsList != null && depIdsList.size() > 0) {
            queryWrapper.in("department_id", depIdsList);
        }
        Integer depCount = personMapper.selectCount(queryWrapper);
        return depCount;
    }

    @Override
    public List<PersonModel> getPersonName() {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name");
        return personMapper.selectList(queryWrapper);
    }

    @Override
    public PersonModel selectById(int parseInt) {
        return personMapper.selectById(parseInt);
    }

    @Override
    public PersonModel selectByName(String contacts, String contactInformation) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("name", contacts).eq("phone", contactInformation);
        return personMapper.selectOne(queryWrapper);
    }

    /**
     * 政治面貌饼状图查询
     * @return
     */
    @Override
    public List<NameAndValueVo> zzmmPieCount() {
        //处理默认未知类型会有多中的情况
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.zzmmPieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("政治面貌未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("政治面貌未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;

    }

    /**
     * 学历饼状图统计
     * @return
     */
    @Override
    public List<NameAndValueVo> educationTextPieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.educationTextPieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("学历未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("学历未知");
            vo0.setValue(count);
            voList.add(vo0);
        }

        return voList;
    }

    /**
     * 人员岗位层级饼状图
     * @return
     */
    @Override
    public List<NameAndValueVo> positionLevelPieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.positionLevelPieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("岗位层级未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("岗位层级未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }

    /**
     * 军官衔级饼状图统计
     * @return
     */
    @Override
    public List<NameAndValueVo> officerPieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.officerPieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("军衔等级未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("军衔等级未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }

    /**
     * 人员类型饼状图
     * @return
     */
    @Override
    public List<NameAndValueVo> personTypePieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.personTypePieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("人员类型未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("人员类型未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }

    /**
     * 人员衔级饼状图
     * @return
     */
    @Override
    public List<NameAndValueVo> rankTitlePieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = personMapper.soldierRankTitlePieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("军衔等级未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("军衔等级未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }

    /**
     * 人员的批量删除
     * @param ids
     * @return
     */
    @Override
    public Result<Object> deletePersonBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            personMapper.updateBacheByIds(idsList,0);
            //update biao where a=?,b=? set A =? ,B = ?
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }

    @Override
    public List<PersonModel> listExport() {
        QueryWrapper<PersonModel> personModelQueryWrapper = new QueryWrapper<>();
        personModelQueryWrapper.eq("status",1);
        return personMapper.selectList(personModelQueryWrapper);
    }

    @Override
    public List<PersonModel> newListExport(List<String> personList) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        for (int i = 0; i < personList.size(); i++) {
            queryWrapper.select().or().eq("id", personList.get(i));
        }
        queryWrapper.orderByAsc("id");
        List<PersonModel> personModelList = personMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public List<PersonModel> otherPersonList(List<Integer> idList) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        if (idList.size() <= 0) {
            queryWrapper.select("id", "name", "department_id", "position_desc", "gender");
        } else {
            queryWrapper.select("id", "name", "department_id", "position_desc", "gender").in("department_id", idList);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("id");
        List<PersonModel> personModelList = personMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public List<PersonModel> getStatisticsByIds(List<Integer> idList, String key) {
        QueryWrapper<PersonModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(key, "COUNT(*) as count");
        if (idList == null && idList.size() <= 0) {
            queryWrapper.select();
        } else {
            for (int i = 0; i < idList.size(); i++) {
                queryWrapper.or().eq("department_id", idList.get(i));
            }
        }
        queryWrapper.ne("status", 0);
        queryWrapper.groupBy(key);
        List<PersonModel> personModelList = personMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public void update(PersonModel model) {
        personMapper.updateById(model);
    }

    @Override
    public Integer insert(PersonModel model) {
        int insert = personMapper.insert(model);
//        AdminUserModel adminUserModel = new AdminUserModel();
//        if (model.getIsHost() !=null) {
//            adminUserModel.setRoles(model.getIsHost());
//        }
//        adminUserModel.setPersonId(model.getId());
//        adminUserModel.setAccount(model.getName());
//        String salt = "gz_b";
//        String pwd1 = md5Hex("jsxl_123456" + salt);
//        adminUserModel.setPwd(pwd1);
//        adminUserModel.setRealName(model.getName());
//        adminUserModel.setStatus(1);
//        adminUserModel.setDepartmentId(model.getDepartmentId());
//        adminUserModel.setDepartmentName(model.getDepartmentText());
//        adminUserService.insert(adminUserModel);
        return insert;
    }

    @Override
    public void delete(int id) {
        personMapper.deleteById(id);
    }

    /**
     * 得到当前日期的年份
     *
     * @return YYYY
     */
    public static String getCurrentDateOfYear() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY");
        String times = sdf.format(date);
        return times;
    }

//
//    @Override
//    public void delete(int id) {
//        roleMapper.deleteById(id);
//    }
}
